<script setup lang="ts">
import {useRoute, useRouter} from 'vue-router'
import {computed, onBeforeMount, onMounted, onUpdated, reactive, ref} from "vue";
import {
  addCart,
  findAllByUidOrByUidAndBid,
  getBusinessByBusinessId,
  listFoodByBusinessId,
  removeCartByData, updateQuantity
} from "../network/api.ts";


const route = useRoute()
const router = useRouter()
let businessId = route.query.businessId
let business = ref({  //这里必须使用ref才能响应式赋值字典, 否则会出bug
  businessId:'',
  businessName:'',
  businessAddress:'',
  businessExplain:'',
  bussinessImg:'',
  orderTypeId:1,
  starPrice:0.0,
  deliveryPrice:0.0,
  remarks:'',
  quantity:1
})
let food = reactive({
    foodId:0,
    foodName:'',
    foodExplain:'',
    foodImg:'',
    remarks:'',
    foodPrice:0,
    bussinessid:0,
    quantity:0
})

let foodArr = ref([food])
let user = sessionStorage.getItem("user")  //但不能根据这个user对象来获取user值  :)乐色
let url = "http://localhost:8080"


onBeforeMount(()=>{
  console.log("onMounted: userId="
      +sessionStorage.getItem("userId")
      +" "+"user="+user
      +" "+"(证明不能根据这个user对象来获取user值 )user.userId="+user.userId
      +" "+"从businessList页传来的 businessId="+businessId
  )

  getBusinessByBusinessId(businessId)
      .then(res=>{
        if(res.data.code!=555){
          business.value = res.data.result
          console.log("获取到的business对象的图片"+business.value.bussinessImg
              +" "+"business.businessId="+business.value.businessId)
          // console.log("获取到的business对象"+business.value
          //     +" "+"business.businessId="+business.value.businessId)
        }else{
          router.push("/serviceDown")
        }

  })

  listFoodByBusinessId(businessId)
      .then((res=>{
        foodArr.value = res.data.result
        console.log("获取到的foodArr数组:")
        console.log(foodArr.value)
        console.log("foodArr[0].foodId="+foodArr.value[0].foodId)
        for(let foodItem of foodArr.value){
          foodItem.quantity = 0
        }
        //如果已登录，那么需要去查询购物车中是否已经选购了某个食品
        if(user!=null){
          console.log("执行listCart")
          listCart();
        }
      })).catch(error=>{
        console.log(error)
  })
})

function listCart(){
  let data = reactive({
    uid:sessionStorage.getItem("userId"),
    bid: businessId
  })
  findAllByUidOrByUidAndBid(data).then(res=>{
    let carArr = res.data.result
    console.log("获取到的carArr:")
    console.log(carArr)
    for(let foodItem of foodArr.value){ //通过 of 取到数组里面的对象
      foodItem.quantity = 0; //初始: 用户没有购买这个商品, 即为0
      for(let cartItem of carArr){
        if(cartItem.foodId == foodItem.foodId){
          foodItem.quantity = cartItem.quantity;
        }
      }
    }
    foodArr.value = sortByKey(foodArr.value,'quantity')
    console.log(foodArr.value)
  }).catch(error=>{
    console.error(error)
  })
}
function sortByKey(ary,key){
  return ary.sort(function (a,b){
    let x = a[key]
    let y = b[key]
    return ((x>y)? -1 : (x<y) ? 1 : 0)
  })
}
function add(index){
  if(user==null){
    router.push({
      path:'/login'
    })
    return ;
  }
  if(foodArr.value[index].quantity==0){
    saveCart(index); //0+1操作  做创建
  }else{
    updateCart(index, 1);//n+1操作
  }
}

function minus(index){
  if(user==null){
    router.push({
      path:'/login'
    })
    return ;
  }
  if(foodArr.value[index].quantity>1){
    updateCart(index, -1);
  }else{
    removeCart(index);
  }
}

function saveCart(index){
  let data = reactive({
    uid:sessionStorage.getItem("userId"),
    bid:businessId,
    fid:foodArr.value[index].foodId
  })
  addCart(data).then(res=>{
    if(res.data.code!=404){//成功创建一个cart
      console.log("成功创建一个cart")
      foodArr.value[index].quantity = 1
      foodArr.value.sort()

    }else{
      alert('向购物车中添加食品失败！');
      console.log('向购物车中添加食品失败！');
    }
  }).catch(error=>{
    console.error(error)
  })
}

function updateCart(index, num){
  let uid = sessionStorage.getItem("userId")
  let bid = businessId
  let fid = foodArr.value[index].foodId
  let quantity = foodArr.value[index].quantity+num

  updateQuantity(uid,bid,fid,quantity).then(res=>{
      if(res.data.code!=404){
        foodArr.value[index].quantity += num
        foodArr.value.sort()
        console.log("数量设为:"+quantity)
      }else{
        alert('向购物车中添加食品失败！');
        console.log('向购物车中添加食品失败！');
      }
    }).catch(error=>{
      console.error(error)
  })
}

function removeCart(index){
  let data = reactive({
    uid:sessionStorage.getItem("userId").toString(), //uid String
    bid:businessId,
    fid:foodArr.value[index].foodId //Integer
  })
  removeCartByData(data).then(res=>{
    if(res.data.code==200){
      //此食品数量要更新为0；视图的减号和数量要消失
      foodArr.value[index].quantity=0;
      foodArr.value.sort();
      console.log("成功删除此食品")
    }else{
      alert('从购物车中删除食品失败！');
    }
  }).catch(error=>{
    console.error(error);
  });
}

function toOrder(){
  router.push({
    path:"/orders",
    query:{businessId:business.value.businessId}
  })
}

let totalPrice = computed(()=>{  //返回一个ref对象, 使用的时候用 .value
  let total = 0
  for(let item of foodArr.value){
    total += item.foodPrice*item.quantity
  }
  return total
})

let totalQuantity = computed(()=>{
  let quantity = 0
  for(let item of foodArr.value){
    quantity += item.quantity
  }
  return quantity
})
//结算价格
let totalSettle = computed(()=>{
  return totalPrice.value + business.value.deliveryPrice
})

onUpdated(()=>{
  console.log(totalSettle.value)
})
</script>

<template>
<!--  <div>??</div>-->
  <div class="wrapper w-full h-full">

    <!-- header部分 -->
    <header>
      <p>商家信息</p>
    </header>

    <!-- 商家logo部分 -->
    <div class="business-logo">
      <img :src="business.businessImg">
    </div>

    <!-- 商家信息部分 -->
    <div class="business-info">
      <h1>{{ business.businessName }}</h1>
      <p>&#165;{{ business.starPrice }} 起送 &#165;{{ business.deliveryPrice }} 配送</p>
      <p>{{ business.businessExplain }}</p>
    </div>

    <!-- 食品列表部分 -->
    <ul class="food">
      <li v-for="(item,index) in foodArr">
        <div class="food-left">
          <img :src="item.foodImg">
          <div class="food-left-info">
            <h3>{{ item.foodName }}</h3>
            <p>{{ item.foodExplain }}</p>
            <p>&#165;{{ item.foodPrice }}</p>
          </div>
        </div>
        <div class="food-right">
          <div class="fa-minus-circle" v-show="item.quantity!=0" @click="minus(index)">
            <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24"><path fill="currentColor" d="M17 13H7v-2h10m-5-9A10 10 0 0 0 2 12a10 10 0 0 0 10 10a10 10 0 0 0 10-10A10 10 0 0 0 12 2Z"/></svg>
          </div>
          <p>
            <span v-show="item.quantity!=0">
              {{ item.quantity }}
            </span>
          </p>
          <div class="fa-plus-circle" @click="add(index)">
            <svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24"><path fill="currentColor" d="M11 17h2v-4h4v-2h-4V7h-2v4H7v2h4v4Zm1 5q-2.075 0-3.9-.788t-3.175-2.137q-1.35-1.35-2.137-3.175T2 12q0-2.075.788-3.9t2.137-3.175q1.35-1.35 3.175-2.137T12 2q2.075 0 3.9.788t3.175 2.137q1.35 1.35 2.138 3.175T22 12q0 2.075-.788 3.9t-2.137 3.175q-1.35 1.35-3.175 2.138T12 22Z"/></svg>
          </div>
        </div>

      </li>
    </ul>

    <!-- 购物车部分 -->
    <div class="cart">
      <div class="cart-left">
        <div class="cart-left-icon"
             :style="totalQuantity==0 ? 'background-color:#505051;' : 'background-color:#3190E8;'">
          <svg class="fa-shopping-cart" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256"><path fill="currentColor" d="M96 216a16 16 0 1 1-16-16a16 16 0 0 1 16 16Zm88-16a16 16 0 1 0 16 16a16 16 0 0 0-16-16Zm46.44-132.75A8 8 0 0 0 224 64H48.32l-8.11-28.4A16.08 16.08 0 0 0 24.82 24H8a8 8 0 0 0 0 16h16.82L61 166.59A24.11 24.11 0 0 0 84.07 184h96.11a23.89 23.89 0 0 0 22.94-16.94l28.53-92.71a8 8 0 0 0-1.21-7.1Z"/></svg>
          <div v-show="totalQuantity!=0"
              class="cart-left-icon-quantity" >
            {{ totalQuantity }}</div>
        </div>

      </div>
      <div class="cart-left-info">
        <p>&#165;{{ totalPrice }}</p>
        <p>另需配送费{{ business.deliveryPrice }}元</p>
      </div>
      <div class="cart-right">
        <!-- 不够起送费 -->
        <div class="cart-right-item"
          v-show="totalSettle<business.starPrice" style="background-color: #535356;cursor: default;">
          &#165;{{business.starPrice}}起送
        </div>
        <!-- 达到起送费 -->
        <div class="cart-right-item"
             @click="toOrder"
             v-show="totalSettle>=business.starPrice">
          去结算
        </div>
      </div>
    </div>

  </div>
</template>

<style scoped>
.wrapper header{
  @apply w-full h-12vw bg-[#0097ff] flex justify-around items-center text-white text-[4.8vw] fixed left-0 top-0 z-1000;
}

.wrapper .business-logo{
  @apply w-full h-[35vw] mt-12vw flex justify-center items-center;
}
.wrapper .business-logo img{
  @apply w-40vw h-30vw rounded-5px;
}

.wrapper .business-info{
  @apply w-full h-20vw flex flex-col justify-center items-center;
}
.wrapper .business-info h1{
  @apply text-5vw;
}
.wrapper .business-info p{
  @apply text-3vw text-#666 mt-1vw ;
}

.wrapper .food{
  @apply  w-full pb-16vw;
}
.wrapper .food li{
  @apply w-full box-border p-2.5vw select-none flex justify-between;
}
.wrapper .food li .food-left{
  @apply flex items-center gap-4;
}
.wrapper .food li .food-left img{
  @apply w-20vw h-20vw;
}
.wrapper .food li .food-left .food-left-info{
  @apply ml-3vw;
}
.wrapper .food li .food-left .food-left-info h3{
  @apply text-3.8vw text-#555;
}
.wrapper .food li .food-left .food-left-info p{
  @apply text-3vw text-#888 mt-2vw;
}
.wrapper .food li .food-right {
  @apply w-16vw flex justify-between items-center;
}

.wrapper .food li .food-right .fa-minus-circle{
  @apply w-5.5vw text-#999 cursor-pointer;
}
.wrapper .food li .food-right p{
  @apply text-3.6vw text-#333;
}
.wrapper .food li .food-right .fa-plus-circle{
  @apply text-5.5vw text-#0097EF cursor-pointer;
}

.wrapper .cart{
  @apply w-full h-14vw fixed bottom-0 flex bg-gray-5 gap-4 justify-between;
}
.wrapper .cart .cart-left{
  @appyly flex bg-gray-5 grow justify-between items-center ;
}
.wrapper .cart .cart-left .cart-left-icon{
  @apply  w-14vw h-14vw box-border border-solid border-#444-1 rounded-8vw bg-#3190E8 text-7vw text-white flex justify-center items-center ml-2vw relative;
}
.wrapper .cart .cart-left .cart-left-icon-quantity{
  @apply w-5vw h-5vw rounded-2.5vw bg-red text-white text-3.6vw flex justify-center items-center absolute right--1.5vw top--1.5vw;
}
.wrapper .cart .cart-left-info{
  @apply ml--25vw mt-1vw;
}
.wrapper .cart .cart-left-info p:first-child{
  @apply text-4.5vw text-white mt-1vw;
}
.wrapper .cart .cart-left-info p:last-child{
  @apply text-2.8vw text-#aaa;
}

.wrapper .cart .cart-right{
  @apply flex bg-#38ca73 w-30vw justify-between;
}
/*达到起送费时的样式*/
.wrapper .cart .cart-right .cart-right-item{
  @apply w-full h-full text-white text-4.5vw font-700 select-none cursor-pointer flex justify-center items-center;
}

</style>